<?php

namespace addons\Expense\common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use common\models\merchant\Member;
use addons\Flow\common\models\Metadata;
use addons\Flow\common\models\Status;
use addons\Flow\common\models\Works;

/**
 * This is the model class for table "{{%addon_expense}}".
 *
 * @property int $id 编号
 * @property int $cate_id 分类
 * @property string $title 标题
 * @property string $content 内容
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class Expense extends ActiveRecord
{
    public $suggest;

    public function behaviors()
    {
        return [
            [
                'class' => \raoul2000\workflow\base\SimpleWorkflowBehavior::className(),
                'defaultWorkflowId' => 'Expense',
                'propagateErrorsToModel' => true,
            ],
            [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
        ];
    }
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%addon_expense}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['cate_id','content','amount','status'], 'required'],
            [['merchant_id','cate_id',  'created_at', 'updated_at','member_id','remind'], 'integer'],
            [['state','suggest','status'], 'string', 'max' => 32],
            [['content'], 'string', 'max' => 255],
            [['amount'], 'number', 'min' => 0],
            [['log','covers'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '编号',
            'member_id' => '用户',
            'cate_id' => '报销类型',
            'content' => '报销原因',
            'amount' => '报销金额',
            'covers' => '报销凭证',
            'suggest' => '审批意见',
            'remind' => '提醒',
            'log' => '审批记录',
            'state' => '工作流状态',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }


    /**
     * 关联用户
     *
     * @return \yii\db\ActiveQuery
     */
    public function getMember()
    {
        return $this->hasOne(Member::class, ['id' => 'member_id']);
    }
    public function getCate()
    {
        return $this->hasOne(ExpenseCate::class, ['id' => 'cate_id']);
    }
    public function beforeSave($insert)
    {
        if(Yii::$app->id == 'backend'||Yii::$app->id == 'merchant')
            $member_id = Yii::$app->user->id;
        else
            $member_id = Yii::$app->user->identity->member_id;
        if($insert){
            $this->member_id = $member_id;
            $this->merchant_id = Yii::$app->user->identity->merchant_id;
            $this->content = $this->cate->title.'报销申请,报销金额:'.$this->amount.'元,事由:'.$this->content;
        }
        if (!$insert){
            $arr = $this->log?$this->log:[];
            $log=["id"=>$member_id,"time"=>time(),"action"=>$this->status,"suggest"=>$this->suggest];
            array_push($arr,$log);
            $this->log = json_encode($arr);
            $status = explode('/',$this->status);
            $this->state = $status[1];

        }

        return parent::beforeSave($insert);
    }
    public function afterSave($insert, $changedAttributes)
    {
        if(Yii::$app->id == 'backend'||Yii::$app->id == 'merchant')
            $member_id = Yii::$app->user->id;
        else
            $member_id = Yii::$app->user->identity->member_id;
        // 增加关联的记录
        if ($insert) {
            $status = explode('/',$this->status);
            $works = new Works();
            $works = $works->loadDefaultValues();
            $works->content = $this->content;
            $works->member_id = $member_id;
            $works->workflow_id = $status[0];
            $works->state = $status[1];
            $works->work_id = $this->id;
            $works->model = '\addons\Expense\common\models\Expense';
            $works->merchant_id = Yii::$app->user->identity->merchant_id;
            $works->save();

            $model = self::findOne($this->id);
            $model->state = $status[1];
            $model->save();
        }
        //更新工作状态
        if (!$insert){
            $status = explode('/',$this->status);
            $works = Works::find()->andWhere(['workflow_id'=>$status[0],'work_id'=>$this->id])->one();
            $works->state = $status[1];
            $audit = Status::find()->andWhere(['workflow_id' => $status[0], 'id' =>$status[1], 'merchant_id' =>Yii::$app->user->identity->merchant_id ])->one();
            $metadata = Metadata::find()->andWhere(['workflow_id' => $status[0], 'status_id' =>$status[1], 'merchant_id' =>Yii::$app->user->identity->merchant_id ])->asArray()->all();
            //某状态设置了元数据启用单独审核
            $flag = 0;
            if($metadata){
                //记录审核人员ID: 1,2,5...
                if($works->audit_ids){
                    if($works->audit_id>0){
                        $audit_ids = explode(',', $works->audit_ids);
                        array_push($audit_ids, $works->audit_id);
                        $works->audit_ids = implode(',',$audit_ids);
                    }
                }else
                    $works->audit_ids = $works->audit_id;
                //记录结束
                foreach ($metadata as $meta){
                    if($meta['key']=='amount') $amount = $meta['value'];
                    if($this->amount<$amount) $flag=1;
                }
                if($flag==0) {
                    if($audit->type==0&&$audit->audit_id) $works->audit_id = $audit->audit_id;
                    else if($audit->type==1&&$audit->role_id)  $works->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($member_id,$audit->role_id);
                }
                if($flag==1) {
                    $works->audit_id = 0;
                    if($status[1]!='refused'){//流程状态置agree
                        $state = 'agree';
                        $model = self::findOne($this->id);
                        $model::updateAll(['state'=>$state,'status' =>$works->workflow_id.'/agree'], ['id' =>$this->id]);
                        $works->state=$state;
                    }
                }
            }
            //某状态未设置元数据的情况
            if(!$metadata) {
                //记录审核人员ID: 1,2,5...
                if($works->audit_ids){
                    if($works->audit_id>0){
                        $audit_ids = explode(',', $works->audit_ids);
                        array_push($audit_ids, $works->audit_id);
                        $works->audit_ids = implode(',',$audit_ids);
                    }
                }else
                    $works->audit_ids = $works->audit_id;
                if($audit->type==0&&$audit->audit_id) $works->audit_id = $audit->audit_id;
                else if($audit->type==1&&$audit->role_id)  $works->audit_id = Yii::$app->merchantsService->member->getLeaderRoleId($member_id,$audit->role_id);
            }
            //判断流程是否结束,status=true表示已经结束
            $state=true;
            foreach ($this->getNextStatuses() as $key => $nextStatus) {
                $state = false;
            }
            if($state) $works->audit_id = 0;
            $works->save();
            //推送短信或消息
            if($this->remind==0&&$works->audit_id>0&&Yii::$app->merchantsService->member->getMember($works->audit_id)->mobile) Yii::$app->services->sms->send(Yii::$app->merchantsService->member->getMember($works->audit_id)->mobile, \addons\Flow\common\enums\WorkflowEnum::getValue($status[1]), 'audit');
            if($this->remind==1&&$works->audit_id>0) Yii::$app->services->backendNotify->createMessage('[报销]'.$this->content, $member_id, $works->audit_id);

        }
        parent::afterSave($insert, $changedAttributes);
    }
    public function afterFind()
    {
        $this->log = json_decode($this->log);
        parent::afterFind(); // TODO: Change the autogenerated stub
    }
}
